<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Ajax实现文件下载</title>
	</head>
	<body>
		<!-- <a href="reload.cmd">reload.cmd</a> -->
		<!-- <input type="text" value="客户信息.xls" id="url" style="width: 500px;"> -->
		<button onclick="submitExport()">下载</button>
	</body>
</html>
<script type="text/javascript">
	function submitExport() {
		download('pc/3_物业/0_填报/收入成本/盈亏对比/全科目_公司明细bak.cpt', {
			"project": "nmXHdc/YRCGAIajNzkTirsznrtQ=",
			"com": "1LIAAACBWNDM567U",
			"et": 202110,
			fine_username: 'root',
			qy: '1',
			op: "write",
			format: "excel",
			extype: "simple",
			__filename__: "导出"
		}, '导出文件.xlsx');
	}

	function download(viewlet, params, fileName) {
		if (!viewlet) {
			alert("请指定导出的模板文件");
			return;
		}
		var xhr = new XMLHttpRequest();
		let url = `/webroot/decision/view/report?viewlet=${viewlet}`;
		//构造参数
		for (let key in params) {
			url += `&${key}=${params[key]}`;
		}
		xhr.open("post", url, true);
		xhr.responseType = 'arraybuffer';

		xhr.onsuccess = function() {
			console.log("请求成功")
			console.log(this);
		}
		xhr.onload = function() {
			console.log(this)
			//let blob = this.response;
			if (this.status == 200) {
				const blob = new Blob([this.response], {
					type: "arraybuffer"
				})
				const downloadElement = document.createElement('a')
				let href = window.URL.createObjectURL(blob)
				downloadElement.href = href

				downloadElement.download = fileName;
				document.body.appendChild(downloadElement)
				downloadElement.click()
				document.body.removeChild(downloadElement) // 下载完成移除元素
				window.URL.revokeObjectURL(href) // 释放掉blob对象
			}
		}
		xhr.send();
	}

	// for (var i = 0; i < 10; i++) {
	// 	download();
	// }

	//responseType设置测试
</script>
